package com.trade.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import com.trade.form.UserForm;
import com.trade.model.Role;
import com.trade.model.User;
import com.trade.service.IUserService;

/**
 * @author Lin Yang
 * 
 */
public class LoginAction extends DispatchAction {
    private IUserService userService;

    public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserForm userForm = (UserForm) form;

        String userName = userForm.getLoginName().trim();
        String password = userForm.getPassword().trim();
        User user = userService.getUser(userName);

        if (null != user) {
            if (!user.getPassword().equals(password)) {
                ActionErrors errors = new ActionErrors();
                errors.add("fail", new ActionMessage("密码不正确", false));
                this.addErrors(request, errors);
                return mapping.getInputForward();
            }

            request.getSession().setAttribute("userName", userName);
            request.getSession().setAttribute("actualName", user.getName());
            Role role = user.getRole();
            request.getSession().setAttribute("roleId", role.getRoleId());
            request.getSession().setAttribute("roleName", role.getName());
            request.getSession().setAttribute("roleDescription", role.getDescription());
            request.getSession().setAttribute("loginUser", user);
            return mapping.findForward("main");
        } else {
            ActionErrors errors = new ActionErrors();
            errors.add("fail", new ActionMessage("用户不存在", false));
            this.addErrors(request, errors);
            return mapping.getInputForward();
        }
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

}
